package TCP;


import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * Tcp实现客户端
 */
public class TcpEchoClient {
    String Serverip;
    int port;
    Socket socket=null;

    public TcpEchoClient(String serverip, int port) throws IOException {
        Serverip = serverip;
        this.port = port;
        this.socket = new Socket(serverip,port);
    }
    public void start(){

        Scanner scanner=new Scanner(System.in);
        //2.把这个读取的内容构造成请求，发给服务器
        try (InputStream inputStream=socket.getInputStream();
             OutputStream outputStream=socket.getOutputStream()){
            while (true){
                //1.从键盘上读取
                String request=scanner.next();
                if(request.equals("exit")){
                    return;
                }
                //2.把键盘上的内容构造成请求，发给服务器
                PrintWriter printWriter=new PrintWriter(outputStream);
                printWriter.println(request);
                printWriter.flush();
                //3.从服务器上得到响应并解析
                Scanner respScanner=new Scanner(inputStream);
                String response=respScanner.next();
                //4.把结果显示到界面上
                String log=String.format("req:%s; resp:%s",request,response);
                System.out.println(log);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient=new TcpEchoClient("127.0.0.1",9090);
        tcpEchoClient.start();
    }
}
